package notes.java.juc.demo;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

import org.junit.Test;

// 将大任务分解成多个小任务，再将各个小任务合并成一个
public class K15_TestForkJoinPool {

	public static void main(String[] args) {

		// 创建一个ForkJoin线程池
		ForkJoinPool pool = new ForkJoinPool();

		ForkJoinTask<Long> task = new ForkJoinSumCalculate(0L, 50000000000L);

		Long sum = pool.invoke(task);

		System.out.println(sum);

	}

	@Test
	public void test1() {

		long sum = 0L;

		for (long i = 0L; i <= 50000000000L; i++) {
			sum += i;
		}

		System.out.println(sum);

	}

}

class ForkJoinSumCalculate extends RecursiveTask<Long> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -259195479995561737L;

	private long start;
	private long end;

	private static final long THURSHOLD = 10000L; // 临界值

	public ForkJoinSumCalculate(long start, long end) {
		this.start = start;
		this.end = end;
	}

	@Override
	protected Long compute() {
		long length = end - start;

		if (length <= THURSHOLD) {
			long sum = 0L;

			for (long i = start; i <= end; i++) {
				sum += i;
			}

			return sum;
		} else {
			long middle = (start + end) / 2;

			ForkJoinSumCalculate left = new ForkJoinSumCalculate(start, middle);
			left.fork(); // 进行拆分，同时压入线程队列

			ForkJoinSumCalculate right = new ForkJoinSumCalculate(middle + 1, end);
			right.fork(); //

			return left.join() + right.join(); // 合并
		}
	}

}
